package com.samphanie.auiu.biz_detail.biz.goods

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.samphanie.auiu.BuildConfig
import com.samphanie.auiu.biz_detail.api.goodsApiService
import com.samphanie.auiu.common.ui.component.base.BaseViewModel
import com.samphanie.auiu.library.restful.AuiuCallback
import com.samphanie.auiu.library.restful.AuiuResponse
import com.samphanie.auiu.pub_mod.model.GoodsDetailModel
import com.samphanie.auiu.pub_mod.model.GoodsFavorite

/**
 * @author ZSY
 */
class GoodsDetailViewModel(val goodsId: String?) : BaseViewModel() {

    fun queryGoodsDetailData(): LiveData<GoodsDetailModel?> {
        val pageData = MutableLiveData<GoodsDetailModel?>()
        if (goodsId!!.isNotBlank()) {
            goodsApiService().queryGoodsDetail(goodsId)
                .enqueue(object : AuiuCallback<GoodsDetailModel> {
                    override fun onSuccess(response: AuiuResponse<GoodsDetailModel>) {
                        if (response.successful() && response.data != null) {
                            pageData.postValue(response.data)
                        } else {
                            pageData.postValue(null)
                        }
                    }

                    override fun onFailed(throwable: Throwable) {
                        pageData.postValue(null)
                        if (BuildConfig.DEBUG) {
                            throwable.printStackTrace()
                        }
                    }
                })
        }
        return pageData
    }

    fun toggleFavorite(): LiveData<Boolean?> {
        val toggleFavoriteData = MutableLiveData<Boolean?>()
        if (goodsId!!.isNotBlank()) {
            goodsApiService().favoriteGoods(goodsId).enqueue(object : AuiuCallback<GoodsFavorite> {
                override fun onSuccess(response: AuiuResponse<GoodsFavorite>) {
                    toggleFavoriteData.postValue(response.data?.isFavorite)
                }

                override fun onFailed(throwable: Throwable) {
                    toggleFavoriteData.postValue(null)
                }

            })
        }
        return toggleFavoriteData
    }

}